package com.lianniu.web.baseService.user.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.lianniu.redis.RedisUtils;
import com.lianniu.web.base.BaseResult;
import com.lianniu.web.baseService.user.model.BuyerinfoVo;
import com.lianniu.web.baseService.user.model.FrontUserVo;
import com.lianniu.web.baseService.user.model.Supply;
import com.lianniu.web.baseService.user.service.IBuyerService;
import com.lianniu.web.baseService.user.service.IFrontUserService;
import com.lianniu.web.baseService.user.service.ISupplyService;
import com.lianniu.web.constants.UserErrorCode;
import com.lianniu.web.util.MD5Util;


@Controller
@RequestMapping(" /rest/frontUser")
public class FrontUserRestController {
    private final static Logger logger = Logger.getLogger(FrontUserRestController.class);

    @Autowired
    private IFrontUserService frontUserService;
    @Autowired
    private ISupplyService supplyService;
    @Autowired
    private IBuyerService buyerService;


    @RequestMapping(value = {"/frontUserAdd"}, method = RequestMethod.POST)
    @Transactional
    public
    @ResponseBody
    BaseResult frontUserAdd(HttpServletRequest request, FrontUserVo frontUserVo) {
        logger.info("FrontUserRestController frontUserAdd begin.");
        logger.info("FrontUserRestController frontUserAdd:" + JSON.toJSONString(frontUserVo));
        try {
            logger.info("frontUserAdd begin.");
            String password = request.getParameter("loginPassWord");
            String supplyName = request.getParameter("supplyName");
            String address = request.getParameter("address");
            String mobile = request.getParameter("mobile");
            if (password != null) {
                String loginPassWord = MD5Util.getMD5String(password);
                frontUserVo.setLoginPassWord(loginPassWord);
            }
            frontUserVo.setDelFlag("1");
            frontUserVo.setUserName(mobile);
            BaseResult baseResult = frontUserService.insertFrontUser(frontUserVo);
            Supply supply = new Supply();
            supply.setUserId(frontUserVo.getUsersId());
            supply.setProvince(frontUserVo.getLiveProvince());
            supply.setCity(frontUserVo.getLiveCity());
            supply.setCounty(frontUserVo.getLiveCounty());
            supply.setShopName(supplyName);
            supply.setAddress(address);
            supply.setDelFlag("1");
            supplyService.addSupply(supply);
            logger.info("frontUserAdd baseResult:" + JSON.toJSONString(baseResult));
            logger.info("frontUserAdd end.");
            return baseResult;

        } catch (Exception e) {
            logger.error("frontUserAdd error:" + e.getMessage());
            logger.info("FrontUserRestController frontUserAdd end.");
            return BaseResult.exception(e.getMessage());
        }
    }

    @RequestMapping(value = {"/buyerAdd"}, method = RequestMethod.POST)
    @Transactional
    public
    @ResponseBody
    BaseResult buyerAdd(HttpServletRequest request, FrontUserVo frontUserVo) {
        logger.info("FrontUserRestController buyerAdd begin.");
        logger.info("FrontUserRestController buyerAdd:" + JSON.toJSONString(frontUserVo));
        try {
            logger.info("buyerAdd begin.");
            String password = request.getParameter("loginPassWord");
            String buyerName = request.getParameter("buyerName");
            String compName = request.getParameter("compName");
            String address = request.getParameter("address");
            String mobile = request.getParameter("mobile");
            if (password != null) {
                String loginPassWord = MD5Util.getMD5String(password);
                frontUserVo.setLoginPassWord(loginPassWord);
            }
            frontUserVo.setDelFlag("1");
            frontUserVo.setUserName(mobile);
            frontUserVo.setCategoryId("1");
            BaseResult baseResult = frontUserService.insertFrontUser(frontUserVo);
            BuyerinfoVo buyer = new BuyerinfoVo();
            buyer.setUserId(frontUserVo.getUsersId());
            buyer.setProvince(frontUserVo.getLiveProvince());
            buyer.setCity(frontUserVo.getLiveCity());
            buyer.setCounty(frontUserVo.getLiveCounty());
            buyer.setBuyerName(buyerName);
            buyer.setCompName(compName);
            buyer.setBuyerTel(mobile);
            buyer.setAddress(address);
            buyer.setDelFlag("1");
            buyer.setBuyerStatus("1");
            buyerService.insertBuyerinfoVo(buyer);
            logger.info("buyerAdd baseResult:" + JSON.toJSONString(baseResult));
            logger.info("buyerAdd end.");
            return baseResult;
        } catch (Exception e) {
            logger.error("buyerAdd error:" + e.getMessage());
            logger.info("FrontUserRestController buyerAdd end.");
            return BaseResult.exception(e.getMessage());
        }
    }

    @RequestMapping(value = {"/checkCode"}, method = RequestMethod.POST)
    public
    @ResponseBody
    String checkCode(HttpServletRequest request) {
        String result = "0";
        RedisUtils redisUtil = new RedisUtils();
        String code = request.getParameter("code");
        String codeUuid = request.getParameter("codeUuid");
        @SuppressWarnings("static-access")
        String checkCode = redisUtil.get("codeUuid:" + codeUuid);
        if (code != checkCode && !code.equals(checkCode)) {
            result = "0";
        } else {
            result = "1";
        }
        return result;
    }

    @RequestMapping("/getFrontUser")
    public
    @ResponseBody
    BaseResult getFrontUser(HttpServletRequest request) {
        String usersId = request.getParameter("usersid");
        logger.info(String.format("get %s frontUser", usersId));
        BaseResult frontUser = frontUserService.getUser(usersId);
        logger.info("get frontUser result : " + JSON.toJSONString(frontUser));
        return frontUser;
    }

    /**
     * @param username
     * @param newpasswd
     * @param codeUuid
     * @param code
     * @return
     * @Title: forgetPass
     * @Description: 忘记密码
     * @author: lzz
     * @date: 2016年8月15日 下午4:07:37
     * @return: BaseResult
     */
    @RequestMapping(value = {"forgetPass"}, method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResult forgetPass(String username, String newpasswd, String codeUuid, String code) {
        logger.info("forgetPass begin.");
        BaseResult result = frontUserService.forgetPwd(username, newpasswd, codeUuid, code);
        logger.info("forgetPass end.");
        return result;
    }

    /**
     * @param username
     * @param oldpasswd
     * @param newpasswd
     * @param codeUuid
     * @param code
     * @return
     * @Title: updatePwd
     * @Description: 修改密码
     * @author: lzz
     * @date: 2016年8月15日 下午4:09:10
     * @return: BaseResult
     */
    @RequestMapping(value = {"/updatePwd"}, method = RequestMethod.POST)
    @ResponseBody
    public BaseResult updatePwd(String username, String oldpasswd, String newpasswd, String codeUuid, String code) {
        logger.info("updatePwd begin.");
        BaseResult result = frontUserService.updatePwd(username, oldpasswd, newpasswd, codeUuid, code);
        logger.info("updatePwd end.");
        return result;
    }

    @RequestMapping(value = {"/checkPhone"}, method = RequestMethod.POST)
    @ResponseBody
    public BaseResult checkPhone(String phone, String supply) {
        boolean b = frontUserService.isExistMobile(phone, supply);
        BaseResult result;
        if (b) {
            result = BaseResult.fail(UserErrorCode.UserNotExistErrorRetCode, UserErrorCode.UserNotExistErrorRetInfo);
        } else {
            result = BaseResult.success();
        }
        return result;
    }

    @RequestMapping(value = {"/updatePic"}, method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResult updatePic(HttpServletRequest request) {
        logger.info("updatePic begin.");
        String userId = request.getParameter("userId");
        Long usersId = Long.parseLong(userId);
        String identyCardPath = request.getParameter("identyCardPath");
        FrontUserVo frontUser = new FrontUserVo();
        frontUser.setUsersId(usersId);
        frontUser.setPicPath(identyCardPath);
        BaseResult baseResult = frontUserService.updateHeadById(frontUser);
        if (frontUser.getPicPath() != null) {
            baseResult.setData(identyCardPath);
        }
        logger.info("updatePic end.");
        return baseResult;
    }

    @RequestMapping(value = {"/getPic"}, method = RequestMethod.POST)
    public
    @ResponseBody
    BaseResult getPic(HttpServletRequest request) {
        logger.info("getPic begin.");
        String userId = request.getParameter("userId");
        BaseResult frontUser = frontUserService.getPicById(userId);
        logger.info("getPic end.");
        return frontUser;
    }

    /**
     * @param request
     * @return
     * @Title: isExisBuyerMobile
     * @Description: TODO
     * @author: guoconglin
     * @date: 2016年8月20日 下午12:03:02
     * @return: boolean
     */
    @RequestMapping(value = {"/isExistBuyerMoble"}, method = RequestMethod.GET)
    public
    @ResponseBody
    boolean isExisBuyerMobile(HttpServletRequest request) {
        logger.info("FrontUserRestController isExistBuyerMoble begin.");
        String mobile = request.getParameter("mobile");
        logger.info("mobile=" + mobile);
        try {
            logger.info("isExistBuyerMoble begin.");
            boolean exitFlg = buyerService.isExistMobile(mobile);
            logger.info("isExistBuyerMoble end.");
            logger.info("FrontUserRestController isExistBuyerMoble end.");
            return exitFlg;
        } catch (Exception e) {
            logger.info("isExistBuyerMoble error:" + e.getMessage());
            logger.info("FrontUserRestController isExistBuyerMoble end.");
            return false;
        }
    }

    @RequestMapping(value = {"/checkBuyerPhone"}, method = RequestMethod.POST)
    @ResponseBody
    public BaseResult checkBuyerPhone(String phone) {
        boolean b = buyerService.isExistMobile(phone);
        BaseResult result;
        if (b) {
            result = BaseResult.fail(UserErrorCode.UserNotExistErrorRetCode, UserErrorCode.UserNotExistErrorRetInfo);
        } else {
            result = BaseResult.success();
        }
        return result;
    }
}
